<?php

/**
 *  朋友关系类
 */
class friendsModel
{
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->db = & $this->base->db;
        $this->redis = & $this->base->redis;
        // $this->base->load('client');
    }
    // 好友关系状态码
    static $friendsAddStatus=array(
                            '0' => '无好友关系',
                            '1' => '已发送好友请求，待对方同意',
                            '2' => '两人是好友关系',
                            '3' => '对方已发送好友请求，待自己同意'
        );
    // 好友排行榜类型
    static $friendsStandingsType=array(
                            '0' => 'month',
                            '1' => 'week'
        );
    /**
     * 搜索用户
     * @param  $nickname 用户昵称
     * @return   array()
     */
    public function searchUsers($nickname)
    {
        $result = array();
        $nickname = trim($nickname);
        //$uid = $this->db->getOne("select uid from r_user where nickname = '{$nickname}' limit 1");
        //empty($uid) && $uid = '';
        $res = $this->base->load('xunSearch')->init('user')->search("$nickname",'uid',1,1);
        $uid = empty($res)? '':$res[0]->uid;
        $result['uid'] = $uid;
        return $result;
    }
    /**
     * 发送添加好友请求
     * @param  $uid 好友请求发起者
     * @param  $add_uid 被请求添加好友者
     * @param  $add_type 添加来源类型 0: 普通 1: 二维码 2: 邀请
     * @return   array()
     */
    public function requestAddFriend($uid,$add_uid,$add_type =0)
    {
        $userInfo = $_ENV['client']->getUserInfo($add_uid);
        if(!$userInfo || empty($uid))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        !in_array($add_type, array('0','1','2')) && $add_type = 0;
        $add_time = $last_update = time();
        $status = 1;
        $data = $this->db->getRow("select * from r_add_friend where uid = '{$uid}' and add_uid = '{$add_uid}' limit 1");
        if($data && $data['status'] != 0) // 申请添加好友记录已存在
        {
            if($add_type > 0)
            {
                if($data['status'] == 2)
                {
                    $static = 2;
                    $rel = true;
                }
                else
                {
                    $rel = $this->buildFriends($uid, $add_uid, $add_type);
                    $rel && $status = 2;
                }
                return array('uid' => $add_uid, 'status' => $status);
            }
            $updateData =array();
            $status = $data['status'];
            if($status == 1) // 已发送好友申请
            {
                $updateData['uid'] = $uid;
                $updateData['add_uid'] = $add_uid;
                $updateData['last_update'] = $last_update;
                // 小红点
                $this->redis->hset(REDIS_PREFIX.'IsNewFriends', $add_uid, 1);
                $this->addPushFriend($uid, array('uid'=>$add_uid, 'status'=>1, 'last_update' => $last_update));
                $this->addPushFriend($add_uid, array('uid'=>$uid, 'status'=>3, 'last_update' => $last_update));

                //发送消息
                $this->sendMessage($uid, $add_uid, 'F1');
            }
            elseif($status == 2) // 已是好友
            {
                $status = 2;
            }
            elseif($status == 3) // 对方已发送好友申请，此时两人的好友关系为待自己同意状态，向双方推消息
            {
                $updateMyData = array(  'uid' => $uid,
                                        'add_uid' => $add_uid,
                                        'last_update' => $last_update,
                                        'status' => 3,
                        );
                $this->db->updateRowTable('r_add_friend', $updateMyData);
                $this->addPushFriend($add_uid, array('uid'=>$uid, 'status'=>3, 'last_update' => $last_update));
                // 更新被申请人信息
                $updateTaData = $updateMyData;
                $updateTaData['uid'] = $add_uid;
                $updateTaData['add_uid'] = $uid;
                $this->db->updateRowTable('r_add_friend', $updateTaData);
                $this->addPushFriend($add_uid, array('uid'=>$uid, 'status'=>3, 'last_update' => $last_update));

                //发送消息
                $this->sendMessage($uid, $add_uid, 'F1');
            }
        }
        else
        {
            $status = 1;
            if($add_type > 0)
            {
                $build_rel = $this->buildFriends($uid, $add_uid, $add_type);
                if($build_rel)
                {
                    $status = 2;
                    return array('uid' => $add_uid, 'status' => $status);
                }
            }
            $insertMyData = compact('uid','add_uid','add_time','last_update');
            $insertMyData['status'] = $status;
            $rel = $this->db->insertRowTable('r_add_friend', $insertMyData);
            if($rel)
            {
                $insertTaData = array(  'uid' => $add_uid,
                                        'add_uid' => $uid,
                                        'add_time' => $add_time,
                                        'last_update' => $last_update,
                                        'status' => 3,
                        );
                $this->db->insertRowTable('r_add_friend', $insertTaData);
                // 小红点
                $this->redis->hset(REDIS_PREFIX.'IsNewFriends', $add_uid, 1);
                // 新的朋友消息
                $this->addPushFriend($uid, array('uid' => $add_uid,'last_update' => $last_update,'status' => 1));
                $this->addPushFriend($add_uid, array('uid' => $uid,'last_update' => $last_update,'status' => 3));

                //$this->sendNoticeMessage($uid,$add_uid,"添加你为好友");
                //
                $this->sendMessage($uid, $add_uid, 'F1');
            }   
        }
        return array('uid' => $add_uid, 'status' => $status);
    }

    /**
     * 发送新的朋友消息
     * @param  [type] $toUserId [description]
     * @param  [type] $data     [description]
     * @return [type]           [description]
     */
    private function sendMessage($sourceUserId, $targetUserId, $descType,$type = 1){

        $category = "1";
        $send_id = "S10001";
        $source_id = $sourceUserId; 
        $target_id = $targetUserId;
        $descType = $descType;
        $content = "";

        //如果是$descType＝F1 类型的发送人、接收人相同, 并且是为处理的情况下。不在发送添加好友请求
        $rst = $this->getIsSendMessageByF1($descType, $source_id, $target_id);
        
        if($rst){
            $this->base->load('message')->insertMessage($category, $send_id ,$source_id ,$target_id ,$descType, $content,  $type);
        }
    }
    /**
     * 判断是添加好友的状态下 descType = F1 的,防止多次发送
     * @return [type] [description]
     */
    private function getIsSendMessageByF1($descType, $source_id, $target_id){
        if("F1" != $descType){
            return true;
        }

        $result = $this->base->db->getRow("select * from r_message_record where category = '1' and send_id = 'S10001' and is_send = '1' and type = '1' and status = '0' and is_before = '0'  and source_id = '".$source_id."' and target_id = '" . $target_id . "' and descType = '" . $descType . "'  ");
        //如果存在,则返回false
        if($result){
            return false;
        }
        return true;
    }

    /**
     * 更新操作类型消息状态
     * @param  [type] $categroy  [description]
     * @param  [type] $source_id [description]
     * @param  [type] $target_id [description]
     * @return [type]            [description]
     */
    public function updateMessage($categroy, $source_id, $target_id, $desc, $status = 1){
        $this->base->load('message')->updateMessageByStatus($categroy, $source_id, $target_id ,$desc, $status);
    }

    /**
     * 同意好友申请
     * @param  $uid 用户uid
     * @param  $accept_uid 好友 uid
     * @return
     */
    public function confirmToAddFriend($uid,$accept_uid)
    {
        if(empty($uid) || empty($accept_uid))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }

        $status = $this->db->getOne("select status from r_add_friend where uid = '{$uid}' and add_uid='{$accept_uid}'");
        empty($status) && $status = 0;
        if($status == 3)
        {
            $rel = $this->buildFriends($uid, $accept_uid);
            $rel && $status = 2;
        }
        elseif($status == 2)
        {
            $status = 2;
        }
        return array('uid' => $accept_uid, 'status' => $status);
    }
    /**
     * 获取好友列表
     * @param  $uid 用户uid
     * @param  $f_id  f_id
     * @return
     */
    public function getFriendsList($uid, $f_id=0,$p =0)
    {
        if(empty($uid))
        {
            return $result;
        }
        $result = array();
        $redisKey = REDIS_PREFIX.'Friends_'.$uid;
        if(!$this->redis->exists($redisKey))
        {
            $this->createFriendListRedis($uid);
        }
        if($p)
        {
            $num = $this->redis->zcard($redisKey);
            //分页
            empty($offset) && $offset = 20;
            require FILE . 'lib/page.class.php';
            $page = new Page($num, $offset);
            $pageStr = $page->show();
            $this->base->view->assign('pageStr', $pageStr);

            $start = ($p - 1) * $offset;
            $sql = "select * from r_friends where uid = '{$uid}' order by add_time DESC limit $start,$offset";
            $data = $this->db->getAll($sql);
            // 数据处理暂略
        }
        else
        {
            $f_id = intval($f_id);
            if(empty($f_id))
            {
                $friends_uids = $this->redis->ZREVRANGEBYSCORE($redisKey, '+inf', '-inf', array('withscores' => TRUE));
            }
            else
            {
                $friends_uids = $this->redis->ZRANGEBYSCORE($redisKey, '('.$f_id, '+inf',array('withscores' => TRUE));
            }

            if($friends_uids)
            {
                !empty($f_id) && arsort($friends_uids);
                foreach ($friends_uids as $f_uid => $record_id)
                {
                    $userInfo = $this->base->load('client')->getUserInfo($f_uid);
                    if($userInfo)
                    {
                        $friendInfo=array(  'record_id' => $record_id,
                                            'uid' => $f_uid,
                                            'header' => $userInfo['header'],
                                            'nickname' => $userInfo['nickname'],
                                            'remark' => $this->getRemark($uid, $f_uid)
                                );
                    }
                    if(isset($friendInfo)) {
                        $result[] = $friendInfo;
                    }
                    unset($friendInfo);
                }
            }
        }
        return $result;
    }
    /**
     * 生成用户好友列表redis数据
     * @param  $uid 用户id
     * @return boolen
     */
    public function createFriendListRedis($uid)
    {
        $redisKey = REDIS_PREFIX.'Friends_'.$uid;

        $data = $this->db->getAll("select record_id, f_uid from r_friends where uid = '{$uid}' and status = 1");

        if($data)
        {
            foreach ($data as $v) {
                $friendInfo = $this->base->load('client')->getUserInfo($v['f_uid']);
                if($friendInfo)
                {
                    $this->redis->ZADD($redisKey, $v['record_id'], $v['f_uid']);
                }
            }
        }
        
        return true;
    }
    /**
     * 添加用户新朋友记录
     * @param  $uid 好友请求发起者
     * @param  $pushArray 好友关系变动信息
     * @return
     */
    public function addPushFriend($uid,$pushArray)
    {
        $redisKey = REDIS_PREFIX.'FriendPush_'.$uid;
        $this->redis->hset($redisKey, $pushArray['uid'], json_encode($pushArray));
    }
    /**
     * 获取用户新朋友记录
     * @param  $uid 好友请求发起者
     * @param  boolen $all 是否返回所有好友申请信息
     * @return
     */
    public function getPushFriend($uid, $all = false)
    {
        $result = array();
        $redisKey = REDIS_PREFIX.'FriendPush_'.$uid;
        if($all)
        {
            $data = $this->db->getAll("select add_uid as uid, status, last_update from r_add_friend where uid = '{$uid}' and (status = 3 or status=1) order by record_id DESC");
        }
        else
        {
            $data = $this->redis->hgetall($redisKey);
        }
        if($data)
        {
            foreach ($data as & $value) {
                $all === false && $value = json_decode($value, true);
                $userInfo = $this->base->load('client')->getUserInfo($value['uid']);
                if($userInfo)
                {
                    $value['nickname'] = $userInfo['nickname'];
                    $value['header'] = $userInfo['header'];
                    $result[] = $value;
                }
            }
        }
        return $result;
    }
    /**
     * 建立好友关系
     * @param  $uid 用户1 id
     * @param  $f_uid 用户2 id
     * @param  $add_type 添加类型 0: 普通，1: 二维码，2: 邀请
     * @return
     */
    public function buildFriends($uid, $f_uid, $add_type=0)
    {
        $result = false;
        $redisKey = REDIS_PREFIX.'Friends_';
        $add_time = $update_time = time();
        $status = 1;
        $data = compact('add_time', 'update_time','status','add_type');
        $myData = $taData = $data;
        $myData['uid'] = $uid;
        $myData['f_uid'] = $f_uid;
        $taData['uid'] = $f_uid;
        $taData['f_uid'] = $uid;
        $myInsertId = $this->db->insertRowTable('r_friends', $myData);
        $taInsertId = $this->db->insertRowTable('r_friends', $taData);
        if($myInsertId && $taInsertId)
        {
            $addData = array('last_update' => $update_time, 'status'=>2);
            $myAddData = $taAddData = $addData;
            $myAddData['uid'] = $uid;
            $myAddData['add_uid'] = $f_uid;
            $taAddData['uid'] = $f_uid;
            $taAddData['add_uid'] = $uid;
            $this->db->updateRowTable('r_add_friend', $myAddData);
            $this->db->updateRowTable('r_add_friend', $taAddData);
            $this->redis->zadd($redisKey.$uid, $myInsertId, $f_uid);
            $this->redis->zadd($redisKey.$f_uid, $taInsertId, $uid);
            // 排行榜
            $redisMonthKey = REDIS_PREFIX .'friendMilStangdsmonth'.date("n").'_';
            $redisWeekKey = REDIS_PREFIX .'friendMilStangdsweek'.date("W").'_';
            $this->redis->exists($redisMonthKey.$uid) && $this->redis->del($redisMonthKey.$uid);
            $this->redis->exists($redisWeekKey.$uid) && $this->redis->del($redisWeekKey.$uid);
            $this->redis->exists($redisMonthKey.$f_uid) && $this->redis->del($redisMonthKey.$f_uid);
            $this->redis->exists($redisWeekKey.$f_uid) && $this->redis->del($redisWeekKey.$f_uid);

            $this->addPushFriend($f_uid, array('uid'=>$uid, 'status'=>2, 'last_update' => $update_time));
            $this->addPushFriend($uid, array('uid'=>$f_uid, 'status'=>2, 'last_update' => $update_time));

            //更新消息状态
            $this->updateMessage('1', $f_uid, $uid, 'F1');
            //发送IM信息
            $this->sendMessage($uid, $f_uid, 'F2',0);
            
            $result = true;
        }
        return $result;
    }

    /**
     * 删除好友
     * @param  $uid 用户uid
     * @param  $del_uid 好友 uid
     * @return
     */
    public function delMyfriend($uid, $del_uid)
    {
        if(empty($uid) || empty($del_uid))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $last_update = time();
        $is_friends = $this->redis->zrevrank(REDIS_PREFIX.'Friends_'.$uid, $del_uid);
        if($is_friends !== false)
        {
            $status = 2;
            if($this->db->delDataTable('r_friends', "uid = '{$uid}' and f_uid ='{$del_uid}'"))
            {
                $status = 0;
                $this->redis->zrem(REDIS_PREFIX.'Friends_'.$uid, $del_uid); // 移出朋友列表
                // 删除排行榜数据
                $this->redis->zrem(REDIS_PREFIX.'friendMilStangdsmonth'.date("n").'_'.$uid, $del_uid);
                $this->redis->zrem(REDIS_PREFIX.'friendMilStangdsweek'.date("W").'_'.$uid, $del_uid);

                $this->redis->zrem(REDIS_PREFIX.'Friends_'.$del_uid, $uid);// 移出朋友列表
                // 删除排行榜数据
                $this->redis->zrem(REDIS_PREFIX.'friendMilStangdsmonth'.date("n").'_'.$del_uid, $uid);
                $this->redis->zrem(REDIS_PREFIX.'friendMilStangdsweek'.date("W").'_'.$del_uid, $uid);

                $this->db->delDataTable('r_friends', "uid = '{$del_uid}' and f_uid ='{$uid}'");
                $this->db->updateRowTable('r_add_friend', array('uid'=>$uid, 'add_uid' =>$del_uid,'status'=>0,'last_update'=>$last_update));
                $this->db->updateRowTable('r_add_friend', array('uid'=>$del_uid, 'add_uid' =>$uid,'status'=>0,'last_update'=>$last_update));
                // 向被删除好友消息信息中添加记录
                // $this->addPushFriend($del_uid, array('uid'=>$uid, 'status'=>0, 'last_update' => $last_update));
            }
        }
        else
        {
            $status = $this->db->getOne("select status from r_add_friend where uid = {$uid} and add_uid={$del_uid} limit 1");
            empty($status) && $status =0;
        }
        return array('uid' =>$del_uid, 'status'=>$status);
    }
    /**
     * 获取好友排行榜
     * @param  $uid 用户uid
     * @param  $type 排行榜类型 month:月榜, week:周榜
     * @param  $point 起始点 uid
     * @param  $del_uid 好友 uid
     * @return
     */
    public function getFriendsMilStandings($uid,$type=0,$point=0,$offset=20)
    {
        $userInfo = $this->base->load('client')->getUserInfo($uid);
        if(empty($userInfo) || !isset(self::$friendsStandingsType[$type]))
        {
            $_ENV['error']->getErrors(101);
            exit;
        }
        $type = self::$friendsStandingsType[$type];
        $result = array();
        $type == 'month' && $redisKey = REDIS_PREFIX .'friendMilStangds'.$type.date("n").'_'.$uid;
        $type == 'week' && $redisKey = REDIS_PREFIX .'friendMilStangds'.$type.date("W").'_'.$uid;
        !$this->redis->exists($redisKey) && $this->createFriendMilStands($uid, $type);
        $result['my_rank'] = array(
                'rank' => $this->getMyMilRankInFriends($uid,$redisKey),
                'level' => common::getLevel($userInfo['total_mileage']),
                'nickname' => $userInfo['nickname'],
                'header' => $userInfo['header'],
                'gender' => $userInfo['gender'],
                'total_mileage' => $this->redis->zscore($redisKey, $uid)?$this->redis->zscore($redisKey, $uid) :'0',
                'further' => $this->redis->zcard(REDIS_PREFIX.'Friends_'.$uid) >0 ? $this->getMyMilGapInFriends($uid,$type) : '',
                );
        $rankData = array();
        if($this->redis->zcard(REDIS_PREFIX.'Friends_'.$uid) == 0)
        {
            $result['data'] = $rankData;
            return $result;
        }
        empty($offset) && $offset = 20;
        $limit = array(0, intval($offset));
        $point = empty($point) ? '+inf' : $this->redis->zscore($redisKey, $point);
        empty($point) && $point = '+inf';
        $uids = $this->redis->ZREVRANGEBYSCORE($redisKey, '('.$point, '-inf', array('limit' => $limit));
        if($uids)
        {
            foreach($uids as $k => $v)
            {
                $friendInfo = $this->base->load('client')->getUserInfo($v);
                if(empty($friendInfo))
                {
                    continue;
                }
                $rankData[] = array(
                    'uid' => $v,
                    'rank' => $this->getMyMilRankInFriends($v, $redisKey),
                    'nickname' => $friendInfo['nickname'],
                    'level' => common::getLevel($friendInfo['total_mileage']),
                    'header' => $friendInfo['header'],
                    'gender' => $friendInfo['gender'],
                    'total_mileage' => $this->redis->zscore($redisKey, $v),
                    'total_rate' => $this->getUserTotalRate($v, $type)
                );
            }
        }
        $result['data'] = $rankData;
        return $result;
    }
    /**
     * 获取指定用户在某朋友中跑步里程排名
     * @param int $uid
     * @param string $redisKey
     * @return int
     */
    public function getMyMilRankInFriends($uid,$redisKey)
    {
        $rank = $this->redis->zrevrank($redisKey, $uid);
        $rank = $rank !== FALSE ? $rank + 1 : 0;
        return $rank;
    }
    /**
     * 获取用户在某朋友中与前一名总里程的差
     * @param int $uid
     * @param string $type week/month
     * @return int
     */
    private function getMyMilGapInFriends($uid,$type)
    {
        $redisKey = REDIS_PREFIX .'friendMilStangds'.$type;
        $redisKey .= $type == 'month' ? date("n") : date("W");
        $redisKey .= '_'.$uid;
        $rank = $this->redis->zrevrank($redisKey, $uid);
        $count = $this->redis->zcard($redisKey);
        $typeWords = $type == 'month' ? '本月' : '本周';
        $gapStr = '';
        if($count == 0)
        {
            $gapStr = $typeWords. '尚未跑步，热热身去跑步吧！'; // 均无跑步数据
        }
        elseif($count == 1)
        {
            $gapStr = $rank == 0 ? $typeWords.'好友排行第1名，尚无好友跑步。' :$typeWords.'尚未跑步，快去跑步和好友PK吧！';
        }
        elseif($count > 1)
        {
            if($rank === false)
            {
                $gapStr = $typeWords.'尚未跑步，快去跑步和好友PK吧！';
            }
            elseif($rank === 0)
            {
                $gapStr = $typeWords.'好友排行第1名，恭喜您成为'.$typeWords.'冠军跑者';
            }
            else
            {
                $socreArr = $this->redis->ZREVRANGE($redisKey, $rank - 1, $rank, TRUE);
                $socres = array_values($socreArr);
                $gap = round(abs($socres[0] - $socres[1]), 2);
                $gapStr = $typeWords.'好友排行'.($rank+1).'名，与前一名相差' . $gap . 'km';
            }
        }
        return $gapStr;
    }
    /**
     * 生成用户好友排行
     * @param int $uid
     * @param string $redisKey
     * @return int
     */
    public function createFriendMilStands($uid,$type)
    {
        $result = false;
        if(empty($uid) || !in_array($type, array('week','month')))
        {
            return $result;
        }
        $type == 'month' && $redisKey = REDIS_PREFIX .'friendMilStangds'.$type.date("n").'_'.$uid;
        $type == 'week' && $redisKey = REDIS_PREFIX .'friendMilStangds'.$type.date("W").'_'.$uid;
        $this->redis->del($redisKey);   // 删除当前数据
        $friends_uids = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX.'Friends_'.$uid, '+inf', '-inf');
        !empty($friends_uids) && $friends_uids[] = $uid;
        foreach ($friends_uids as $key => $f_uid) {
            $friendsRunData = $this->base->load('client')->getUserFrRunData($f_uid, $type, true);
            $total_mileage = $friendsRunData['total_mileage'];
            $total_mileage >0 && $this->redis->zadd($redisKey, $total_mileage, $f_uid);
        }
        // 设置有效期
        $expireTime = $type == 'week' ? strtotime("next Monday") : strtotime(date("Y").'-'.(date("m")+1).'-1');
        $expireTime -= time();
        $this->redis->expire($redisKey,$expireTime);
        return $result;
    }
    /**
     * 获取某用户当月（周）跑步总里程
     * @param int $uid
     * @param string $type
     * @return floor
     */
    public function getUserTotalMilieage($uid,$type)
    {
        $data = $this->base->load('client')->getUserFrRunData($uid, $type);
        return $data['total_milieage'];
    }
    /**
     * 获取某用户当月（周）跑步总次数
     * @param int $uid
     * @param string $type
     * @return int
     */
    public function getUserTotalRate($uid,$type)
    {
        $data = $this->base->load('client')->getUserFrRunData($uid, $type);
        return $data['total_rate'];
    }
    /**
     * 获取达人列表
     * @param int $limit 取得达人数量
     * @return array
     */
    public function getTalentUsers($limit = 40)
    {
        $uids = $this->redis->ZREVRANGEBYSCORE(REDIS_PREFIX .'talentUsers', '+inf', '-inf');
        $data = array();
        if($uids)
        {
            $selectUids = array();
            if(count($uids) > $limit)
            {
                foreach (array_rand($uids, $limit) as $key => $v) {
                    $selectUids[] = $uids[$v];
                }
            }
            else
            {
                $selectUids = $uids;
            }
            foreach ($selectUids as $key => $v) {
                $userInfo = $this->base->load('client')->getUserInfo($v);
                if($userInfo)
                {
                    $data[] = array('uid'=>$userInfo['uid'],'nickname'=>$userInfo['nickname'],'gender'=>$userInfo['gender'],'header'=>$userInfo['header'],'level'=>$userInfo['level'],'words'=>'总里程：'.$userInfo['total_mileage'].'km');
                }
            }
        }
        return $data;
    }
    /**
     * 好友信息推送
     * @param int $uid 推送消息接收人
     * @param int $uid 好友状态变化相关用户id
     * @param int $status 好友关系状态
     * @return array
     */
    public function pushFriendsMessage($uid, $f_uid, $status)
    {
        $uid = intval($uid);
        $status = intval($status);
        $userInfo = $this->db->getRow("select cid, lastcid from r_user where uid = '{$f_uid}' limit 1");
        $cid = $userInfo['lastcid'] >0 ? $userInfo['lastcid'] : $userInfo['cid'];
        if(empty($cid) || $this->redis->sismember(REDIS_PREFIX . 'clientNotReceivePush', $cid))
        {
            return;
        }
        $clientInfo = $this->db->getRow("select * from r_client where cid = '{$cid}' and isPushVaild=1");
        if(empty($clientInfo))
        {
            return false;
        }
        $client_type = $clientInfo['client_type'];
        $client = $clientInfo['client'];
        if($client_type == 2 && empty($clientInfo['push_token']))
        {
            return false;
        }
        // 开始推送设置
        $apnsArr = $this->base->config['App_PUSH_INFO'];
        $culr = $apnsArr['host'].':'.$apnsArr['port'];
        $android_post_curl = "http://".$culr.'/droid/notific/'.$apnsArr['appIdentifier'];
        $ios_post_curl = "http://".$culr.'/ios/notific/'.$apnsArr['appIdentifier'];
        $body = $this->redis->hget(REDIS_PREFIX . 'UserInfo_' . $uid, 'nickname');
        $body .= $status == 2 ?'已添加你为好友，快去看看吧！':'申请加你为好友，快去看看吧！';
        $androidData = array(
                'clients' => array($client),
                'expiry' => time() + 3600,
                'payload' => array(
                    'aps' => array(
                        'alert' => array(
                            'body' => $body,
                            'title' => '好友通知',
                            'action-loc-key' => '',
                            'loc-key' => '',
                            'loc-args' => '',
                            'launch-image' => '',
                            ),
                        // 'badge' => 3,
                        'sound' => 0,
                        ),
                    // 'url' => 'joggers://friend',//推送的地址
                    'url' => 'joggers://',//推送的地址
                    'args' => "",
                    ),
        );
        //ios消息推送
        $iosData = array(
                'tokens' => array($clientInfo['push_token']),
                'expiry' => time() + 1800,
                'payload' => array(
                    'aps' => array(
                        'alert' => array(
                            'body' => $body,
                            'action-loc-key' => '',
                            'loc-key' => '',
                            'loc-args' => '',
                            'launch-image' => '',
                            ),
                        // 'badge' => 3,
                        'sound' => 0,
                    ),
                    'url' => 'joggers://friend',
                ),
        );
        if($client_type == 1)
        {
            $postResult = $this->base->load('pushController')->post($android_post_curl, json_encode($androidData)) == '"+OK"' ? 1 : 0;
        }
        elseif($client_type == 2)
        {
            $postResult = $this->base->load('pushController')->post($ios_post_curl, json_encode($iosData)) == '"+OK"' ? 1 : 0;
        }
        if($postResult)
        {
            $this->pushFriendDevicesLog($uid, $f_uid, $body, $client);
        }
        return;
    }
    /**
     * 保存推送的设备
     * @param   int uid  推送消息发起人
     * @param   int f_uid 推送消息接收人
     * @param    string   $message   推送的消息内容
     * @return   void
     */
    private function pushFriendDevicesLog($uid, $f_uid, $message, $client)
    {
        $path = FILE . '../web/log/pushlog/';
        !file_exists($path) && mkdir($path);
        $logName = date('Y-F').'.txt';

        $logInfo = '['.date('Y-m-d H:i:s')."]";
        $logInfo .= '好友消息推送：'. '推送消息发起人id: '.$uid."\t";
        $logInfo .= '推送消息接收人id: '.$f_uid."\t";
        $logInfo .= '推送的消息内容: '.$message."\t";
        $logInfo .= '   设备：'.$client."\n";
        $fp = fopen($path.$logName, "a");
        fwrite($fp, $logInfo);
        fclose($fp);
        return;
    }
    /**
     * 获取推荐好友列表
     * @param
     * @return array()
     */
    public function getRecommendFriendList($uid = 0, $num = 20)
    {
        $result = array();
        $redisKey = REDIS_PREFIX.'RecFriList';

        if(!$this->redis->EXISTS($redisKey))
        {
            $this->createRecommendFriendList();
        }

        if($num > 0)
        {
            $result = $this->getMyRecFriendList($uid, $num);
        }
        else
        {
            $result = $this->redis->SMEMBERS($redisKey);
        }

        empty($result) && $result = array();
        return $result;
    }
    /**
     * 创建推荐好友列表
     * @param
     * @return array()
     */
    private function createRecommendFriendList()
    {
        $recmmendUser = REDIS_PREFIX.'RecFriList';
        $recmmendImg = REDIS_PREFIX.'RecFriendImg';

        $data = $this->db->getall("select uid, recImg from r_friendRecList where status = 2 and recImg != '' order by updatetime DESC");

        $recData = array();
        if($data)
        {
            foreach ($data as $v)
            {
                $recData[$v['uid']][] = $v['recImg'];
            }
            foreach ($recData as $uid => $v)
            {
                if(count($v) == 3)
                {
                    $this->redis->SADD($recmmendUser, $uid);
                    $this->redis->hset($recmmendImg, $uid, json_encode($v));
                }
            }
        }
        return ;
    }

    /**
     * 获取用户的推荐好友列表
     * @param int $uid
     * @return array $recFriendList
     */
    public function getMyRecFriendList($uid = 0, $num = 20)
    {
        $recFriendList = array();
        $redisKey = REDIS_PREFIX.'RecFriList'; 
        $myRecFriListKey = REDIS_PREFIX.'MyRecFriList'; 
        
        if(!$uid || !$this->redis->exists($redisKey))
        {
            return $recFriendList;
        }

        $allRecFriends = $this->redis->SMEMBERS($redisKey);
        if($allRecFriends)
        {
            foreach ($allRecFriends as $v)
            {
                if($this->redis->ZRANK(REDIS_PREFIX.'Friends_'.$uid, $v) === false && $v != $uid)
                {
                    $this->redis->SADD($myRecFriListKey, $v);
                }
            }
            // 随机获取推荐好友
            $recFriendList = $this->redis->SRANDMEMBER($myRecFriListKey, $num);
            $this->redis->del($myRecFriListKey);
        }
        
        return $recFriendList;
    }
    /**
     * 获取推荐好友展示图
     * @param
     * @return array()
     */
    public function getRecFriendImg($uid)
    {
        $result = $this->redis->hget(REDIS_PREFIX.'RecFriendImg', $uid);
        if($result && common::is_json($result))
        {
            $result = json_decode($result, true);
        }
        else
        {
            $result = array();
            $images = $this->db->getCol("select recImg from r_friendRecList where uid = '{$uid}' and status = 2 limit 3");
            if(is_array($images) && count($images) == 3)
            {
                $result = $images;
                $this->redis->hset(REDIS_PREFIX.'RecFriendImg', $uid,  json_encode($images));
            }
        }
        
        return $result;
    }
    /**
     * 获取好友关系状态
     * @param
     * @return int $status
     */
    public function getFriendStatus($my_uid = 0, $target_uid = 0)
    {
        $status = 0;

        if($my_uid > 0 && $target_uid > 0)
        {
            $my_uid = intval($my_uid);
            $target_uid = intval($target_uid);

            $status = $this->db->getOne("select status from r_add_friend where uid='{$my_uid}' and add_uid = '{$target_uid}' limit 1");

            $status = intval($status);
        }

        return $status;
    }
    /**
     * 检查是否为好友关系
     * @param
     * @return int $status
     */
    public function checkFriends($uid = 0, $friendId = 0)
    {
        $uid = intval($uid);
        $friendId = intval($friendId);

        // redis
        $is_friends = $this->redis->zrevrank(REDIS_PREFIX.'Friends_'.$uid, $friendId);

        if($is_friends === false)
        {
            $status = $this->db->getOne("select status from r_friends where uid='{$uid}' and f_uid = '{$friendId}' limit 1");

            $is_friends = $status == 1;
        }

        return $is_friends;
    }
    /**
     * 设置好友备注
     * @param
     * @return int $status
     */
    public function setRemark($uid, $friendId, $remark)
    {
        $result = false;

        $uid = intval($uid);
        $friendId = intval($friendId);
        $remark = trim($remark);

        if(!$uid || !$friendId)
        {
            return $result;
        }

        $friendArr = array('uid' => $uid,
                            'f_uid' => $friendId,
                            'remark' => $remark,
                            'update_time' => $this->base->time
                        );
        if($this->db->updateRowTable('r_friends', $friendArr))
        {
            $result = true;
        }

        return $result;
    }
    /**
     * 获取好友备注
     * @param uid 用户id
     * @param f_uid 好友用户id
     * @return string $remark
     */
    public function getRemark($uid, $f_uid)
    {
        $remark = '';

        $uid = intval($uid);
        $f_uid = intval($f_uid);

        if(!$uid || !$f_uid)
        {
            return $remark;
        }

        $remark = $this->db->getOne("select remark from r_friends where uid = '{$uid}' and f_uid = '{$f_uid}' and status = 1");
        $remark .= '';

        return $remark;
    }

}
?>
